package antLogic;

import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Mark the intern
 * Date: 10-Jul-2007
 * Time: 4:05:51 PM
 */
public class ThoughtProcess {
    Ant host;

    protected ThoughtProcess(Ant host) {
        this.host = host;

    }

    protected synchronized void think() {
        AntManager.antMgr.log(this, "Ant #" + host.getAntId() + " is thinking");
        boolean foundEvent = false;
        Event criticalEvent = new Event(Event.EMPTY, host.stepCount, null);

        for (int criticalEventId : host.criticalEvents) {
            for (int i = host.memory.size(); i > 0; i--) {
                criticalEvent = host.memory.get(i - 1);
                if (criticalEvent.getEventType() == criticalEventId) {
                    AntManager.antMgr.log(this, "Ant #" + host.getAntId() + " is handling event " + criticalEvent.getEventName());
                    foundEvent = true;
                    break;
                }
            }
            if (foundEvent) {
                break;
            }
        }
        if (criticalEvent.getEventType().equals(Event.EMPTY)) {
           AntManager.antMgr.logWarn(this, host.getAntId() + " is expected to think but has no critical event.");
            idle();
        }  else if (criticalEvent.getEventType().equals(Event.BORN)) {
           AntManager.antMgr.log(this, host.getAntId() + " has just been born.");
            host.legs.turnAndWalkForever(0);
            host.criticalEvents = new Vector<Integer>();
            host.criticalEvents.add(Event.MEETOBSTACLE);
            idle();
        }

        else if (criticalEvent.getEventType().equals(Event.MEETOBSTACLE)) {
            AntManager.antMgr.log(this, host.getAntId() + " has encountered an obstacle.");
            host.legs.turnAndWalkForever(45);
            host.criticalEvents = new Vector<Integer>();
            host.criticalEvents.add(Event.MEETOBSTACLE);
            idle();
        }
    }

    private synchronized void idle() {
        host.needsToThink = false;
        host.setPriority(Thread.NORM_PRIORITY);
    }
}
